import { defineStore } from 'pinia';
import { store } from '@/store';
import storage from 'good-storage';
import { theme, tabBar } from '@/constants/modules/app';
import type { ITheme } from '@/constants/modules/app/types';
import { deepClone, fromCamelCase } from '@/utils/lodash';
import { appendStyle } from '@/utils/web';
import { getClientInfo } from '@/utils';
import API_HOME from '@/apis/home';
import API_ORDER from '@/apis/order';
import {showToast} from 'vant'

export interface AppStore {
  theme: NonNullable<ITheme>;
  tabBar: NonNullable<Recordable>;
}

export const useAppStore = defineStore({
  id: 'app',
  state: (): AppStore => ({
    theme: getLocalTheme(),
    tabBar,
  }),
  getters: {
    getTheme: (state) => state.theme,
    getTabBar: (state) => state.tabBar,
  },
  actions: {
    async updateTheme(payload: Recordable = {}) {
      const myTheme: ITheme = { ...deepClone(this.theme), ...payload };

      // 切换主题深/浅
      if (payload.mode === 'system') {
        myTheme.mode = getClientInfo().theme;
      }
      if (myTheme.mode === 'dark') {
        document.documentElement.classList.add('dark');
      } else {
        document.documentElement.classList.remove('dark');
      }

      // 生成主题变量
      const colorVarList = Object.keys(myTheme.colors).map(
        (key) => `--color-${fromCamelCase(key, '-')}: ${myTheme.colors[key]};`,
      );
      const vanVarList = Object.keys(myTheme.vanThemeOverrides).map(
        (key) =>
          `--van-${fromCamelCase(key, '-')}: ${
            myTheme.colors[myTheme.vanThemeOverrides[key]] ?? myTheme.vanThemeOverrides[key]
          };`,
      );

      const cssText = `:root { ${[...colorVarList, ...vanVarList].join('\n')} }`;
      appendStyle(cssText, 'theme');

      this.theme = myTheme;
      storage.set('theme', myTheme);
    },
    /**
     * 切换暗黑模式
     */
    toggleThemeMode() {
      this.updateTheme({
        mode: this.theme.mode === 'dark' ? 'light' : 'dark',
      });
    },
  },
});

export function useAppStoreWithOut() {
  return useAppStore(store);
}

function getLocalTheme() {
  const result = storage.get('theme', theme);
  if (result.version === theme.version) {
    return result;
  } else {
    return theme;
  }
}
export const useShopNav = defineStore({
  id: 'shopNav',
  state: () => ({
    tabBar:[
      
    ],
    // 购物车徽标
    cartList:[ ],
    // 选择要结算的商品
    isCheckList:[],
    goodsChecklist:[],
    badge:0,
    // 优惠券列表
    couponsList:[],
    // 优惠券id
    couponsId:'',
    // 结算页价格信息,
    orderCalc:{},
    // 地址id
    address_id:0,
    // 总件数
    total_Numer:0,
    // 进入结算页的来源
    checkedFrom:'',
    // 支付类型
    payment:'paypal',
  }),
  getters: {
  getTabBar: (state) => state.tabBar,
  getBadge: (state) => state.badge,
  // 获取购物车列表
  getCartList: (state) => state.cartList,
    // 获取选择购物车列表
    getCheckCartList: (state) => state.isCheckList,
    // 结算页商品展示列表
    getGoodsChecklist: (state) => state.goodsChecklist,
    // 优惠券列表
    getCoupons: (state) => state.couponsList,
    // 订单信息
    getOrderCalc: (state) => state.orderCalc,
    // 地址id
    getAddressId:(state)=>state.address_id,
    // 总件数
    getTotal_Numer:(state)=>state.total_Numer
  },
  actions: {
    // 获取购物车列表
    async getCarList(){
       let token = storage.get('token');
      if (!token) {
        console.log('没有token购物车请求失败');
        return 
      }
      const res = await API_HOME.cartList();
      if (res.code === 1) {
        this.cartList = res.data;
      }
    },
    // 获取结算页价格信息  计算价格
     async getCarCheckList(){
        const res = await API_HOME.orderCalc({
          coupon_id:this.couponsId,
          address_id:this.address_id,
         order_type: 'goods',
         goods_list:[...this.isCheckList]  });
      if (res.code === 1) {
        this.orderCalc=res.data
        this.goodsChecklist=res.data.goods_list
        // 计算件数
        this.total_Numer=res.data.goods_list.reduce((total:any, item:any) => {
            return total + item.goods_num;
          }, 0);
      }
    },
    // 获取优惠券列表
    async getCouponsList(){
      let res=await API_HOME.orderCoupons({
        order_type: 'goods',
         goods_list:[...this.isCheckList]
      })
      if (res.code==1) {
        this.couponsList=res.data

      }
    },
    // 设置购物车列表
     setCartList(arr:any){
      this.cartList = arr;
    },
    // 选择的购物车商品
    setCartCheckList(arr:any){
      this.isCheckList = arr;
    },
    //设置地址
    setAddressId(number:any){
      this.address_id=number
    }, 
    // 设置优惠券id
    setCouponsId(number:any){
      this.couponsId=number
    }, 
    // 设置结算来源
    setCheckedFrom(str:any){
      this.checkedFrom=str
    }, 
    // 设置支付方式
    setPayment(str:any){
      this.payment=str
    }, 
    //提交订单    
    async submitOrder(){
        let res=await API_HOME.orderCreate({
            from:this.checkedFrom,
          order_type:'goods',
          coupon_id:this.couponsId,
          address_id:this.address_id,
          goods_list:[...this.isCheckList]
        })
        if (res.code==1) {
          // this.payOrder(res.data.order_sn)
           showToast(res.msg);
          return Promise.resolve(res.data)
        }else{
           return Promise.reject(new Error(res.msg));
        }
        
      } ,
      // 支付
      async payOrder(order_sn:any){
         let pay=await API_ORDER.payPrepay({
            order_sn:order_sn,
            payment:this.payment,
            platform:'H5'
          })
          if (pay.code==1) {
        
          }
          showToast(pay.msg);
      }
  },
});
